package model

import (
	"gorm.io/gorm"
	"time"
)

type (
	ResourceDaoModel interface {
		Insert(res ResourceP) error
		SelectById(userid int) ([]ResourceP, error)
		UpdateCount(userid int, resCount string, resType string) error
		UpdateMaxCount(userid int, MaxCount string, resType string) error
		UpdateAddRate(userid int, AddRate string, resType string) error
	}

	DefaultResourceDao struct {
		conn  *gorm.DB
		table string
	}

	ResourceP struct {
		ResourceId int       `json:"resource_id"`
		UserId     int       `json:"user_id"`
		Type       string    `json:"type"`
		Count      string    `json:"count"`
		MaxCount   string    `json:"max_count"`
		AddRate    string    `json:"add_rate"`
		UpdateTime time.Time `json:"update_time"`
	}
)

func NewDefaultResourceDao(conn *gorm.DB) *DefaultResourceDao {
	return &DefaultResourceDao{
		conn:  conn,
		table: "resource",
	}
}

func (r *DefaultResourceDao) Insert(res ResourceP) error {
	respond := r.conn.Create(&res)
	return respond.Error
}

func (r *DefaultResourceDao) SelectById(userid int) ([]ResourceP, error) {
	var resources []ResourceP
	result := r.conn.Where("user_id = ?", userid).Find(&resources)
	// 检查是否有错误发生
	if result.Error != nil {
		return nil, result.Error
	}
	// 返回查询到的资源列表
	return resources, nil
}

func (r *DefaultResourceDao) UpdateCount(userid int, resCount string, resType string) error {
	err := r.conn.Model(&ResourceP{}).Where("user_id = ? AND type = ?", userid, resType).Update("Count", resCount).Error

	return err
}

func (r *DefaultResourceDao) UpdateMaxCount(userid int, MaxCount string, resType string) error {
	err := r.conn.Model(&ResourceP{}).Where("user_id = ? AND type = ?", userid, resType).Update("max_count", MaxCount).Error

	return err
}

func (r *DefaultResourceDao) UpdateAddRate(userid int, AddRate string, resType string) error {
	err := r.conn.Model(&ResourceP{}).Where("user_id = ? AND type = ?", userid, resType).Update("add_rate", AddRate).Error

	return err
}
